// splay

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 35005;
int n;
struct node {
  int s[2], p, v;
  int cnt;
  void init(int _p, int _v) {
    p = _p;
    v = _v;
    cnt = 1;
  }
} tr[N];
int root, idx;
void rotate(int x) {
  int y = tr[x].p, z = tr[y].p;

  int k = tr[y].s[1] == x;
  tr[x].p = z;
  tr[z].s[tr[z].s[1] == y] = x;
  tr[y].s[k] = tr[x].s[k ^ 1];
  tr[tr[x].s[k ^ 1]].p = y;
  tr[y].p = x;
  tr[x].s[k ^ 1] = y;
}
void splay(int x, int k) {
  while (tr[x].p != k) {
    int y = tr[x].p, z = tr[y].p;
    if (z != k)
      if ((tr[z].s[0] == y) ^ (tr[y].s[0] == x))
        rotate(x);
      else
        rotate(y);
    rotate(x);
  }
  if (k == 0) root = x;
}
void insert(int v) {
  int u = root, p = 0;
  while (u && tr[u].v != v) p = u, u = tr[u].s[v > tr[u].v];
  if (u) {
    tr[u].cnt++;
    return;
  } else {
    u = ++idx;
    if (p) tr[p].s[v > tr[p].v] = u;
    tr[u].init(p, v);
  }
  splay(u, 0);
}
void find(int v) {
  int u = root;
  while (tr[u].v != v && tr[u].s[v > tr[u].v]) u = tr[u].s[v > tr[u].v];
  splay(u, 0);
}
int pre(int v) {
  find(v);
  int u = root;
  if (tr[u].v < v) return u;
  u = tr[u].s[0];
  while (tr[u].s[1]) u = tr[u].s[1];
  return u;
}
int suf(int v) {
  find(v);
  int u = root;
  if (tr[u].v > v) return u;
  u = tr[u].s[1];
  while (tr[u].s[0]) u = tr[u].s[0];
  return u;
}
int main() {
  long long res = 0;
  cin >> n;
  insert(-INF), insert(INF);
  int k;
  cin >> k;
  res += k;
  insert(k);
  for (int i = 2; i <= n; ++i) {
    int k;
    cin >> k;
    insert(k);
    find(k);
    if (tr[root].cnt > 1) continue;
    res += min(abs(k - tr[pre(k)].v), abs(tr[suf(k)].v - k));
  }
  cout << res << '\n';
}
